package com.aaa.power.service.impl;

import com.aaa.common.constants.ReturnCode;
import com.aaa.common.util.Result;
import com.aaa.power.dao.UserRoleDao;
import com.aaa.power.entity.UserRole;
import com.aaa.power.service.UserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户和角色关联表(UserRole)表服务实现类
 *
 * @author makejava
 * @since 2020-11-12 20:30:16
 */
@Service("userRoleService")
public class UserRoleServiceImpl implements UserRoleService {
    @Resource
    private UserRoleDao userRoleDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public Result queryById(Integer userId) {
        List<UserRole> userRoles = this.userRoleDao.queryById(userId);
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(), userRoles);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<UserRole> queryAllByLimit(int offset, int limit) {
        return this.userRoleDao.queryAllByLimit(offset, limit);
    }

    @Override
    public Result queryAll(UserRole userRole) {
        List<UserRole> userRoles = userRoleDao.queryAll(userRole);
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(), userRoles);
    }

    /**
     * 新增数据
     *
     * @param userId 用户ＩＤ
     * @param roleIds 角色ID字符串
     * @return 实例对象
     */
    @Override
    public int insert(Integer userId, String roleIds) {
        this.userRoleDao.deleteById(userId);
        StringBuffer stringBuffer =new StringBuffer();
        //分割字符串，循环拼接values后面  (1,1),(1,2),(1,10)...
        String[] ridArray = roleIds.split(",");
        for (String rid : ridArray) {
            stringBuffer.append("("+userId+","+rid+"),");
        }
        String values=stringBuffer.substring(0,stringBuffer.length()-1);
        return this.userRoleDao.insert(values);
    }

    /**
     * 修改数据
     *
     * @param userRole 实例对象
     * @return 实例对象
     */
    @Override
    public UserRole update(UserRole userRole) {
        this.userRoleDao.update(userRole);
        return (UserRole) this.queryById(userRole.getUserId()).getData();
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {

        return this.userRoleDao.deleteById(userId) > 0;
    }
}